package com.modificial.shiro.config;

import com.modificial.shiro.system.domain.SysRole;
import com.modificial.shiro.system.domain.SysUser;
import com.modificial.shiro.system.exception.ServiceException;
import com.modificial.shiro.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author modificial
 * @date 2018/8/4 0004
 * @company modificial_org
 * @description 权限身份验证数据源配置
 */
@Slf4j
public class IShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 权限验证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("##################执行Shiro权限认证##################");
        //获取当前登录输入的用户名，等价于(String) principalCollection.fromRealm(getName()).iterator().next();
        SysUser sysUser = (SysUser) super.getAvailablePrincipal(principalCollection);
        SysUser user = (SysUser) principalCollection.getPrimaryPrincipal();
        SysUser sysUser1=userService.findUserByName(sysUser.getUserName());
        if(sysUser1==null){
            throw new ServiceException("该用户不存在");
        }
        if (user != null) {
            //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            List<SysRole>roles=userService.findRolesByUser(sysUser1.getUserId());
            List<String>roleList=new ArrayList<>(roles.size());
            roles.forEach(it->{
                roleList.add(it.getRoleName());
            });
            //用户的角色集合
            info.addRoles(roleList);
            //用户的权限集合
            info.addStringPermissions(userService.findPermissionsByUser(sysUser1.getUserId()));

            return info;
        }
        // 返回null的话，就会导致任何用户访问被拦截的请求时，都会自动跳转到unauthorizedUrl指定的地址
        return null;

    }

    /**
     * 身份验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("##################执行Shiro身份认证##################");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        log.info("验证当前Subject时获取到token为：" + token.toString());
        //查出是否有此用户
        SysUser hasUser = userService.findUserByName(token.getUsername());
        if(hasUser!=null&&hasUser.getIsEnable()==0){
            throw new ServiceException("该用户已被禁用");
        }
        if (hasUser != null) {
            String salt=hasUser.getSalt();
            // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
            return new SimpleAuthenticationInfo(hasUser, hasUser.getPassword(),
                    ByteSource.Util.bytes(salt),getName());
        }
        throw new ServiceException("该用户不存在");
    }
}
